#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char * argv[])
{
	
	if(0 < fork())
	{
		exit(0);
	}

	setsid();

	chdir("/");

	umask(0);

	int maxfd = getdtablesize();
	while(maxfd--)
	{
		close(maxfd);
	}

	if(0 < fork())
	{
		exit(0);
	}
//	openlog(argv[0],LOG_CONS | LOG_PID, 0);

////////////////////////////////////////
//利用select超时检测，如果10s内管道中没有消息可读，则认为服务器已挂掉，重启服务器
//1：创建管道文件描述符，
//2：设置监听集合
//3：监听文件描述符，正常则静默，不正常则杀死进程，重启服务器
////////////////////////////////////////

	if(-1 == mkfifo("/root/deamonfifo", 0666) )
	{
		if(EEXIST!= errno)
		{
		//	syslog(LOG_INFO, "mkfifo down\n");
		//	write(sysfd,"mkfifo down\n",13);
//			printf("mkfifo down\n");
			return -1;
		}
	}
//	printf("mkfifo good\n");

	int fd = open("/root/deamonfifo",O_RDWR);
//	if(fd == -1)
//		printf("open fifo failed\n");

//	printf("open fifo good\n");

	int debugfd = open("/root/debug",O_CREAT|O_RDWR,0666);
	int sysfd = open("/root/syslog",O_CREAT|O_RDWR,0666);
//	if(sysfd == -1)
//		printf("open syslog failed\n");
//	printf("open syslog good\n");

	struct timeval timeout = {
		.tv_sec = 10,        /* seconds */			  
		.tv_usec = 0,        /* microseconds */
	};

	fd_set readfds;
	FD_ZERO(&readfds);
	FD_SET(fd, &readfds);
	fd_set temprfds = readfds;
	int server_pid = 0;
//	syslog(LOG_INFO, "deamon  is work, \n");
	write(sysfd,"deamon is work\n",16);

	while(1)
	{
		temprfds = readfds;
		timeout.tv_sec = 10;
		timeout.tv_usec = 0;
//		write(sysfd, "ready to select\n",16);
		if(-1 == select(fd+1, &temprfds, NULL, NULL, &timeout))
		{
			//syslog(LOG_INFO, "deamon:server is work bad, restart it\n");
			exit(-1);

		}
		if(timeout.tv_sec == 0)
		{
			write(sysfd,"deamon is outt\n",16);
			if(server_pid != 0)
			{
				char buf[30] = {0};
				sprintf(buf,"kill -9 %d",server_pid);
				system(buf);
	//			write(sysfd,buf,strlen(buf)+1);
			}
			if(0 == fork())
			{
			//	system("/root/server_app");
			//	exit(0);
				execlp("/root/server_app","/root/server_app",NULL);
			}
			write(sysfd,"restart server\n",16);
			continue;		
		}
//		write(sysfd,"good\n",6);
		read(fd, &server_pid, sizeof(int));
	//	syslog(LOG_INFO, "deamon:server is work normal, pid is 0x%x\n",server_pid);

	}

}

